package com.warren.gulimall.member.service.impl;

import com.warren.common.to.SocialUser;
import com.warren.gulimall.member.dao.MemberLevelDao;
import com.warren.gulimall.member.entity.MemberLevelEntity;
import com.warren.gulimall.member.exception.PhoneExistException;
import com.warren.gulimall.member.exception.UserNameExistException;
import com.warren.gulimall.member.vo.GiteeAccessToken;
import com.warren.gulimall.member.vo.GiteeUserInfo;
import com.warren.gulimall.member.vo.MemberLoginVo;
import com.warren.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.warren.common.utils.PageUtils;
import com.warren.common.utils.Query;

import com.warren.gulimall.member.dao.MemberDao;
import com.warren.gulimall.member.entity.MemberEntity;
import com.warren.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1.数据库查询
        MemberDao dao = this.baseMapper;
        MemberEntity entity = dao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity == null) {
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public void regist(MemberRegisterVo vo) {
        MemberDao dao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        //设置默认用户等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        //检查数据是否唯一,为了让controller感知异常,异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        //密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        dao.insert(entity);
        //其它默认信息
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao dao = this.baseMapper;
        Integer count = dao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        MemberDao dao = this.baseMapper;
        Integer count = dao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameExistException();
        }
    }

    /**
     * 社交登录
     * @param vo
     * @return
     */
    @Override
    public MemberEntity socialLogin(GiteeAccessToken vo){
        GiteeUserInfo giteeUserInfo = vo.getGiteeUserInfo();
        //登录和注册合并逻辑
        String uid = giteeUserInfo.getId()+"";
        //判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        System.out.println("hahahahahahah:" + memberEntity);
        if (memberEntity != null){
            //这个用户已经注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiresIn(vo.getExpires_in()+"");
            memberDao.updateById(update);

            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in()+"");

            return memberEntity;
        }else{
            //没有查到当前社交用户对应的记录我们就要注册一个
            MemberEntity regist = new MemberEntity();
            regist.setNickname(giteeUserInfo.getName());
            regist.setEmail(giteeUserInfo.getEmail());
            regist.setSocialUid(uid);
            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiresIn(vo.getExpires_in()+"");

            memberDao.insert(regist);
            return regist;
        }
    }
}